package com.xf.common.core.authe.feign;

import com.xf.common.core.constant.CommonConstants;
import com.xf.common.core.entity.constant.SecurityConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author JoeyLiu
 * @create 2022-03-23 11:55
 */
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String organizationId = request.getHeader(CommonConstants.ORGANIZATION_ID);
        requestTemplate.header(CommonConstants.ORGANIZATION_ID, organizationId);
        String signupApplication = request.getHeader(CommonConstants.SIGNUPAPPLICATION);
        requestTemplate.header(CommonConstants.SIGNUPAPPLICATION, signupApplication);
        String token = request.getHeader(CommonConstants.Authorization);
        if (token != null && !token.contains(SecurityConstants.BASIC_PREFIX)) {
            requestTemplate.header(HttpHeaders.AUTHORIZATION, SecurityConstants.JWT_PREFIX + token);
        }

    }
}
